<template>
  <div>
    <div style="width:16%;float:left">
      <div style="text-align:center;background: rgb(234, 203, 154);margin-left: 5px;height: 30px;width: 230px;margin-top:24px;">
        <div style="padding-top:5px; ">分类</div>
      </div>
      <a-tree
        v-if="treeData.length"
        :tree-data="treeData"
        :show-line="true"
        :defaultExpandAll="true"
        @select="onSelectClass"
      />
    </div>
    <a-card :bordered="false" style="width:84%;float:right">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24" />
        </a-form>
      </div>
      <!-- 查询区域-END -->

      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button icon="plus" @click="handleAdd">新增</a-button>
        <a-button icon="plus" @click="handleAddAttr">扩展属性</a-button>
        <a-button icon="plus" @click="handleAddRange">共享范围</a-button>
        <a-button icon="delete" @click="batchDel">删除</a-button>
      </div>

      <!-- table区域-begin -->
      <div>
        <!--      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">-->
        <!--        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项-->
        <!--        <a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
        <!--      </div>-->

        <a-table
          ref="table"
          size="middle"
          :scroll="{x:true}"
          bordered
          row-key="id"
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :row-selection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
          class="j-table-force-nowrap"
          @change="handleTableChange"
          :pagination="ipagination"
        >

          <template slot="htmlSlot" slot-scope="text">
            <div v-html="text" />
          </template>
          <template slot="imgSlot" slot-scope="text">
            <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
            <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;">
          </template>
          <template slot="fileSlot" slot-scope="text">
            <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
            <a-button
              v-else
              :ghost="true"
              type="primary"
              icon="download"
              size="small"
              @click="downloadFile(text)"
            >
              下载
            </a-button>
          </template>

          <span slot="action" slot-scope="text, record">
            <a @click="handleEdit(record)">编辑</a>
          </span>

        </a-table>
      </div>

      <hte-file-class-modal ref="modalForm" :parentId="parentId" @ok="modalFormOk" />
      <hte-file-class-attr-modal ref="attrModalForm" />
      <hte-file-class-range-modal ref="rangeModalForm" />
    </a-card>
  </div>
</template>

<script>

import '@/assets/less/TableExpand.less'
// import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import HteFileClassModal from './modules/HteFileClassModal'
import HteFileClassAttrModal from './modules/HteFileClassAttrModal'
import HteFileClassRangeModal from './modules/HteFileClassRangeModal'
import { getAction} from '@/api/manage'

export default {
  name: 'HteFileClassList',
  // mixins:[JeecgListMixin, mixinDevice],
  components: {
    HteFileClassModal,
    HteFileClassAttrModal,
    HteFileClassRangeModal
  },
  data() {
    return {
      parentId:this.$route.params && this.$route.params.id, //库id
      description: '文件分类管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '分类名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '父类名称',
          align: 'center',
          dataIndex: 'parentName'
        },
        {
          title: '管理员',
          align: 'center',
          dataIndex: 'managerName'
        },
        {
          title: '权限',
          align: 'center',
          dataIndex: 'authority',
          customRender: (text) => {
            var str = ''
            if (text && text.indexOf('1') >= 0) {
              str += '查阅,'
            }
            if (text && text.indexOf('2') >= 0) {
              str += '编辑,'
            }
            if (text && text.indexOf('3') >= 0) {
              str += '下载,'
            }
            if (text && text.indexOf('4') >= 0) {
              str += '可废除,'
            }
            if (text && text.indexOf('6') >= 0) {
              str += '可分享,'
            }
            if (str.length > 1) {
              return str.substr(0, str.length - 1)
            }
            return str
          }
        },
        // {
        //   title: '发布方式',
        //   align: 'center',
        //   dataIndex: 'publishWay',
        //   customRender: (text) => {
        //     var str = ''
        //     if (text && text.indexOf('1') >= 0) {
        //       str += '私有组,'
        //     }
        //     if (text && text.indexOf('2') >= 0) {
        //       str += '发送人员,'
        //     }
        //     if (str.length > 1) {
        //       return str.substr(0, str.length - 1)
        //     }
        //     return str
        //   }
        // },
        {
          title: '是否审批',
          align: 'center',
          dataIndex: 'autoPublish',
          customRender: (text) => {
            return text && text == 1 ? '是' : '否'
          }
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createUser'
        },
        // {
        //   title: '可否二级发布',
        //   align: 'center',
        //   dataIndex: 'releaseFlag',
        //   customRender: (text) => {
        //     return text && text == 1 ? '是' : '否'
        //   }
        // },

        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/lib/hteFileClass/list',
        delete: '/lib/hteFileClass/delete',
        deleteBatch: '/lib/hteFileClass/deleteBatch',
        exportXlsUrl: '/lib/hteFileClass/exportXls',
        importExcelUrl: 'lib/hteFileClass/importExcel',
        getTreeList: '/lib/hteFileClass/getTreeList',
      },
      dictOptions: {},
      superFieldList: [],
      treeData: [],

      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        name: '',
        parentId:this.parentId
      },
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: []
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  created() {
    this.ipagination.parentId = this.parentId
    this.initData()
   
  },
  methods: {
    initData(){
      this.loadData()
      this.getSuperFieldList()
      this.loadTree()
    },
    initDictConfig() {
    },
    getSuperFieldList() {
      const fieldList = []
      fieldList.push({ type: 'int', value: 'parentId', text: '父节点' })
      fieldList.push({ type: 'string', value: 'name', text: '名称' })
      fieldList.push({ type: 'string', value: 'authority', text: '大类权限' })
      fieldList.push({ type: 'string', value: 'publishWay', text: '发布方式' })
      fieldList.push({ type: 'string', value: 'autoPublish', text: '自动发布,0:需要审批 1:不需要' })
      fieldList.push({ type: 'string', value: 'createUser', text: '创建人' })
      fieldList.push({ type: 'string', value: 'state', text: '状态 (0 正常 -1 删除)' })
      fieldList.push({ type: 'int', value: 'openFlag', text: '是否公开' })
      fieldList.push({ type: 'int', value: 'defaultDept', text: '所属部门"默认选择, 为0默认选择当前登录人所属部门' })
      fieldList.push({ type: 'string', value: 'managerId', text: '管理员id' })
      fieldList.push({ type: 'int', value: 'releaseFlag', text: '可否二级发布' })
      fieldList.push({ type: 'string', value: 'managerName', text: '管理员名字' })
      this.superFieldList = fieldList
    },
    loadData() {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }

      this.loading = true
      this.dataSource=[]
      let param = Object.assign({}, this.ipagination)
      delete param.pageSizeOptions
      delete param.showTotal
      getAction(this.url.list, param).then((res) => {
        if (res.success) {
          debugger
          this.dataSource = res.result.records || res.result
          this.ipagination.total = this.dataSource.length
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    loadTree() {
      var that = this
      getAction(this.url.getTreeList, { parentId: that.parentId }).then((res) => {
        if (res.success) {
          console.log(res)
          that.treeData = res.result.treeList
          that.treeData.forEach(it=>{
            it.selectable=true
          })
        }
      })
    },
    handleEdit: function(record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.disableSubmit = false
    },
    handleAdd: function() {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
    },
    handleAddAttr: function() {
      if (this.selectionRows.length < 1 || this.selectionRows.length > 1) {
        this.$message.error('请选择一行记录')
        return
      }
      if (!this.selectionRows[0].parentId || this.selectionRows[0].parentId==0) {
        this.$message.error('一级分类不允许设置扩展属性')
        return
      }
      console.log(this.selectionRows[0])
      
      this.$refs.attrModalForm.add(this.selectionRows[0].id)
      this.$refs.attrModalForm.title = '扩展属性'
       this.$refs.attrModalForm.parentId=this.parentId
    },
    handleAddRange: function() {
      if (this.selectionRows.length < 1 || this.selectionRows.length > 1) {
        this.$message.error('请选择一行记录')
        return
      }
       if (!this.selectionRows[0].parentId || this.selectionRows[0].parentId==0) {
        this.$message.error('一级分类不允许设置共享范围')
        return
      }
      this.$refs.rangeModalForm.add(this.selectionRows[0].id)
      this.$refs.rangeModalForm.title = '共享范围'
    },
    handleTableChange(pagination, filters, sorter) {

      this.ipagination = pagination
      // this.ipagination.pageNo = this.ipagination.current
      // this.loadData()
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
     this.initData()
      // 清空列表选中
      // this.onClearSelected()
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onSelectClass(selectedKeys) {
      this.ipagination.parentId = selectedKeys[0]
      this.onClearSelected()
      this.loadData()
    },
    onClearSelected() {
      this.selectedRowKeys = [];
      this.selectionRows = [];
    },
    batchDel: function() {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function() {
            that.loading = true
            getAction(that.url.deleteBatch, { ids: ids }).then((res) => {
              if (res.success) {
                // 重新计算分页问题
                // that.reCalculatePage(that.selectedRowKeys.length)
                that.$message.success(res.message)
                that.initData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })
      }
    },
      reCalculatePage(count){
      //总数量-count
      let total=this.ipagination.total-count;
      //获取删除后的分页数
      let currentIndex=Math.ceil(total/this.ipagination.pageSize);
      //删除后的分页数<所在当前页
      if(currentIndex<this.ipagination.current){
        this.ipagination.current=currentIndex;
      }
      console.log('currentIndex',currentIndex)
    }
  }
}
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
